import React, { Component } from 'react'
import {
  Form,
  Breadcrumb,
  Card,
  Radio,
  Table,
  Button,
  Select,
  DatePicker,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import { ArticleStatus } from '../../api/constants'
import { getChannels } from '../../api/channels'
import { deleteArticles } from 'api/article'
import request from 'utills/request'
import defaultImg from '../../assets/imags/defaultImage.png'
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'

const { Option } = Select
const { RangePicker } = DatePicker

export default class ArticleList extends Component {
  state = {
    channels: [],
    articles: {},
  }

  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(data) {
        return (
          <img
            src={data.images[0] || defaultImg}
            alt=""
            style={{ width: 200, height: 150, objectFit: 'cover' }}
          ></img>
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = ArticleStatus.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => this.handleRevise(data.id)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => this.handleClick(data.id)}
            />
          </Space>
        )
      },
    },
  ]
  componentDidMount() {
    this.getChannelsList()
    this.getArticlesList()
  }
  async getChannelsList() {
    const res = await getChannels()
    this.setState({
      channels: res.data.channels,
    })
  }
  async getArticlesList() {
    this.getArticles()
  }

  //封装 文章 接口
  async getArticles(params) {
    params = params || {}
    const res = await request.get('/v1_0/mp/articles', {
      params,
    })
    // console.log(res.data)
    this.setState({
      articles: res.data,
    })
  }

  //提交表单事件
  onFinish = async ({ status, channel_id, date }) => {
    const queryParams = {}
    if (status !== -1) {
      queryParams.status = status
    }
    if (channel_id !== undefined) {
      queryParams.channel_id = channel_id
    }
    if (date) {
      queryParams.begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
      queryParams.end_pubdate = date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
    }
    queryParams.page = 1
    this.queryParams = queryParams
    console.log('筛选', this.queryParams)
    this.getArticles(queryParams)
  }

  onChange = async (page, pageSize) => {
    console.log(this.queryParams)
    const params = {
      ...this.queryParams,
      page,
      per_page: pageSize,
    }
    this.page = page
    // console.log('改变后的', params)
    this.getArticles(params)
  }

  handleRevise = (id) => {
    // console.log(id)
    this.props.history.push(`/home/publish/${id}`)
  }

  handleClick = (id) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除此篇文章吗？',
      onOk: async () => {
        await deleteArticles(id)
        this.getArticles({
          ...this.queryParams,
          page: this.page || 1,
        })
        message.success('删除成功', 1)
      },
    })
  }

  render() {
    const {
      articles: { page, per_page, results, total_count },
    } = this.state
    return (
      <div>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleStatus.map((item) => (
                  <Radio value={item.id} key={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <Select
                placeholder="请选择文章频道"
                style={{
                  width: 220,
                }}
              >
                {this.state.channels.map((item) => {
                  return (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件共找到${total_count}条结果：`}>
          <Table
            columns={this.columns}
            dataSource={results}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              total: total_count,
              pageSize: per_page,
              current: page,
              onChange: this.onChange,
            }}
          />
        </Card>
      </div>
    )
  }
}
